<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="title"
    :width="1200"
    :maskClosable="false"
    :defaultFullscreen="true"
    :confirmLoading="confirmLoading"
    @ok="handleSubmit"
  >
    <template #default>
      <BasicForm ref="formRef" @register="registerForm" />
      <a-divider style="margin: 1px 0" class="cust-divider" />
      <a-tabs @change="handleChangeTabs" :animated="false" v-model:activeKey="activeKey">
        <a-tab-pane tab="图表配置" :key="refKeys[0]" forceRender>
          <JVxeTable
            ref="onlGraphreportItem"
            toolbar
            row-number
            row-selection
            keep-source
            dragSort
            :height="390"
            :loading="onlGraphreportItemTable.loading"
            :dataSource="onlGraphreportItemTable.dataSource"
            :columns="onlGraphreportItemTable.columns"
          >
            <template #groupType="props">
              <a-select
                v-model:value="props.value"
                :options="groupTypeOptions"
                style="width: calc(100% - 30px); outline: none"
                @change="combinationChange(props)"
              >
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu" />
                  <a-divider style="margin: 4px 0" />
                  <div style="padding: 4px 8px; cursor: pointer" @mousedown="(e) => e.preventDefault()" @click="combinationAddItem()">
                    <plus-outlined />
                    添加组合
                  </div>
                </template>
              </a-select>
              <EditOutlined style="width: 30px" @click="combinationEditItem(props.value)" />
            </template>

            <template #groupStyle="props">
              <a-select v-model:value="props.value" :options="groupStyleOptions" style="width: 100%" @change="groupStyleChange(props)">
                <template #dropdownRender="{ menuNode: menu }">
                  <v-nodes :vnodes="menu" />
                </template>
              </a-select>
            </template>

            <!-- <template #toolbarSuffix>
              <a-button preIcon="ant-design:menu-outlined" @click="handleGroup">分组管理</a-button>
            </template> -->
          </JVxeTable>
        </a-tab-pane>
        <a-tab-pane tab="图表查询" :key="refKeys[1]" forceRender>
          <a-alert type="info" show-icon class="alert">
            <template #message>
              <span>图表查询功能暂未实现,先保留此配置页！</span>
            </template>
          </a-alert>
          <JVxeTable
            ref="onlGraphreportQuery"
            toolbar
            row-number
            row-selection
            keep-source
            dragSort
            :height="390"
            :loading="onlGraphreportQueryTable.loading"
            :dataSource="onlGraphreportQueryTable.dataSource"
            :columns="onlGraphreportQueryTable.columns"
          />
        </a-tab-pane>
      </a-tabs>
    </template>
  </BasicModal>
  <GraphreportTempletGroupModal @register="registerGroupModal" @success="handleGroupSuccess" />
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, computed, watch } from 'vue';
  import { useModalInner, BasicModal } from '/@/components/Modal';
  import { FormSchema } from '/@/components/Table';
  import { useForm, BasicForm } from '/@/components/Form/index';
  import { JVxeTable } from '/@/components/jeecg/JVxeTable';
  import { useJvxeMethod } from '/@/hooks/system/useJvxeMethods';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import { Alert } from 'ant-design-vue';
  import { Dropdown, Menu } from 'ant-design-vue';
  import { createAsyncComponent } from '/@/utils/factory/createAsyncComponent';
  import { JVxeTypes, JVxeColumn } from '/@/components/jeecg/JVxeTable/types';
  import { defHttp } from '/@/utils/http/axios';
  import { bindMapFormSchema } from '/@/utils/common/compUtils';
  import { PlusOutlined, EditOutlined } from '@ant-design/icons-vue';
  import GraphreportTempletGroupModal from './GraphreportTempletGroupModal.vue';

  export default defineComponent({
    name: 'GraphreportTempletModal',
    components: {
      BasicModal,
      BasicForm,
      JVxeTable,
      Alert,
      Dropdown,
      Menu,
      MenuItem: createAsyncComponent(() => import('../components/DropMenuItem.vue')),
      MenuDivider: Menu.Divider,
      EditOutlined,
      PlusOutlined,
      VNodes: (_, { attrs }) => {
        return attrs.vnodes;
      },
      GraphreportTempletGroupModal,
    },
    props: {},
    emits: ['register', 'success'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const isUpdate = ref(true);
      const confirmLoading = ref(true);
      const refKeys = ref(['onlGraphreportItem', 'onlGraphreportQuery']);
      const activeKey = ref('onlGraphreportItem');
      const onlGraphreportItem = ref();
      const onlGraphreportQuery = ref();
      const tableRefs = { onlGraphreportItem, onlGraphreportQuery };
      const groupTypeOptions = ref<any>([
        {
          value: '默认分组',
          label: '默认分组',
        },
      ]);
      const groupStyleOptions = ref<any>([
        { label: '卡片', value: 'card' },
        { label: '标签', value: 'tabs' },
      ]);

      const [registerGroupModal, { openModal }] = useModal();

      const mapFormSchema = bindMapFormSchema(
        {
          col_span_one: {
            colProps: {
              xs: 24,
              sm: 8,
            },
            itemProps: {
              labelCol: { xs: 24, sm: 6 },
              wrapperCol: { xs: 24, sm: 18 },
              colon: true,
            },
            style: { width: '100%' },
          },
        },
        'col_span_one'
      );

      const formSchema: FormSchema[] = [
        {
          label: '',
          field: 'id',
          component: 'Input',
          show: false,
        },
        mapFormSchema(
          {
            label: '组合报表名称',
            field: 'templetName',
            component: 'Input',
            dynamicRules: () => {
              return [{ required: true, message: '请输入组合报表名称!' }];
            },
          },
          'col_span_one'
        ),
        mapFormSchema(
          {
            label: '组合报表编码',
            field: 'templetCode',
            component: 'Input',
            dynamicRules: () => {
              return [{ required: true, message: '请输入组合报表编码!' }];
            },
          },
          'col_span_one'
        ),
        mapFormSchema(
          {
            label: '组合报表风格',
            field: 'templetStyle',
            defaultValue: 'tab',
            component: 'JDictSelectTag',
            componentProps: {
              dictCode: 'online_graph_display_template',
              placeholder: '请选择组合报表风格',
              stringToNumber: false,
            },
          },
          'col_span_one'
        ),
      ];

      const graphreportParamColumns: JVxeColumn[] = [
        {
          title: '图表名称',
          key: 'graphreportName',
          type: JVxeTypes.popup,
          width: '300px',
          popupCode: 'online-graph', //从报表配置中获取code值
          fieldConfig: [
            { source: 'name', target: 'graphreportName' },
            { source: 'id', target: 'graphreportId' },
          ],
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '图表编码',
          key: 'graphreportId',
          type: JVxeTypes.input,
          visible: false,
        },
        {
          title: '图表类型',
          key: 'graphreportType',
          type: JVxeTypes.select,
          width: '180px',
          placeholder: '请输入${title}',
          dictCode: 'online_graph_type',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '组合类型',
          key: 'groupTxt',
          type: JVxeTypes.slot,
          width: '200px',
          slotName: 'groupType',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '组合展示风格',
          key: 'groupStyle',
          type: JVxeTypes.slot,
          width: '180px',
          slotName: 'groupStyle',
          validateRules: [{ required: true, message: '${title}不能为空' }],
        },
        {
          title: '是否显示',
          key: 'isShow',
          minWidth: '80px',
          align: 'center',
          type: JVxeTypes.checkbox,
          customValue: [1, 0],
          defaultChecked: true,
        },
        {
          title: '排序',
          key: 'orderNum',
          type: JVxeTypes.inputNumber,
          width: '80px',
          placeholder: '请输入${title}',
          defaultValue: '',
        },
      ];

      const graphreportQueryColumns: JVxeColumn[] = [
        {
          title: '字段名称',
          key: 'field',
          width: 130,
          type: JVxeTypes.input,
          defaultValue: '',
        },
        {
          title: '字段文本',
          key: 'label',
          width: 130,
          type: JVxeTypes.input,
          defaultValue: '',
        },
        {
          title: '控件类型',
          key: 'viewType',
          width: 170,
          type: JVxeTypes.select,
          options: [
            { title: '文本框', value: 'text' },
            { title: '日期(yyyy-MM-dd)', value: 'date' },
            { title: '日期（yyyy-MM-dd HH:mm:ss）', value: 'datetime' },
            { title: '时间（HH:mm:ss）', value: 'time' },
            { title: '下拉框', value: 'list' },
            { title: '下拉多选框', value: 'list_multi' },
            { title: '下拉搜索框', value: 'sel_search' },
            { title: '分类字典树', value: 'cat_tree' },
            { title: 'Popup弹框', value: 'popup' },
            { title: '部门选择', value: 'sel_depart' },
            { title: '用户选择', value: 'sel_user' },
            { title: '省市区组件', value: 'pca' },
            { title: '自定义树控件', value: 'sel_tree' },
          ],
          defaultValue: 'text',
          placeholder: '请选择${title}',
        },
        {
          title: '查询类型',
          key: 'mode',
          width: 110,
          type: JVxeTypes.select,
          options: [
            { title: '普通查询', value: 'single' },
            { title: '范围查询', value: 'group' },
          ],
          defaultValue: 'single',
          placeholder: '请选择${title}',
          validateRules: [{ required: true, message: '请选择${title}' }],
        },
        {
          title: '字典Table',
          key: 'dictTable',
          width: 130,
          type: JVxeTypes.textarea,
          defaultValue: '',
        },
        {
          title: '字典Code',
          key: 'dictCode',
          width: 130,
          type: JVxeTypes.input,
          defaultValue: '',
        },
        {
          title: '字典Text',
          key: 'dictText',
          width: 130,
          type: JVxeTypes.input,
          defaultValue: '',
        },
        {
          title: '默认值',
          key: 'defValue',
          width: 130,
          type: JVxeTypes.input,
          defaultValue: '',
        },
        {
          title: '是否启用',
          key: 'config',
          minWidth: 80,
          type: JVxeTypes.checkbox,
          customValue: ['1', '0'],
          defaultChecked: false,
        },
      ];

      const onlGraphreportItemTable = reactive({
        loading: false,
        dataSource: [],
        columns: graphreportParamColumns,
      });
      const onlGraphreportQueryTable = reactive({
        loading: false,
        dataSource: [],
        columns: graphreportQueryColumns,
      });
      const [registerForm, { setProps, resetFields, setFieldsValue, validateFields, updateSchema }] = useForm({
        schemas: formSchema,
        showActionButtonGroup: false,
      });
      const [handleChangeTabs, handleSubmit, requestSubTableData, formRef] = useJvxeMethod(
        requestAddOrEdit,
        classifyIntoFormData,
        tableRefs,
        activeKey,
        refKeys
      );
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        var _b;
        await reset();
        setModalProps({
          confirmLoading: false,
          showCancelBtn: data == null ? void 0 : data.showFooter,
          showOkBtn: data == null ? void 0 : data.showFooter,
        });
        isUpdate.value = !!(data == null ? void 0 : data.isUpdate);
        if (unref(isUpdate)) {
          await setFieldsValue(Object.assign({}, data.record));
          let params = { headId: (_b = data == null ? void 0 : data.record) == null ? void 0 : _b.id };
          let itemUrl = '/api-online/diagram/diagramCombination/item/listByHeadId';
          requestSubTableData(itemUrl, params, onlGraphreportItemTable);
          let queryUrl = '/api-online/diagram/diagramCombination/query/listByHeadId';
          requestSubTableData(queryUrl, params, onlGraphreportQueryTable);
        }
        setProps({ disabled: !(data == null ? void 0 : data.showFooter) });
      });

      const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      watch(onlGraphreportItemTable, (newVal) => {
        setGroupTypeOptions(onlGraphreportItemTable);
      });

      async function reset() {
        await resetFields();
        activeKey.value = 'onlGraphreportItem';
        onlGraphreportItemTable.dataSource = [];
        onlGraphreportQueryTable.dataSource = [];
      }

      function classifyIntoFormData(allValues) {
        let main = Object.assign({}, allValues.formValue);
        return {
          ...main, // 展开
          onlGraphreportItemList: allValues.tablesValue[0].tableData,
          onlGraphreportQueryList: allValues.tablesValue[1].tableData,
        };
      }

      async function requestAddOrEdit(values) {
        try {
          setModalProps({ confirmLoading: true });
          let items = [],
            querys = [],
            head = {};
          Object.keys(values).map((k) => {
            if (k == 'onlGraphreportItemList') {
              items = values[k];
            } else if (k == 'onlGraphreportQueryList') {
              querys = values[k];
            } else {
              head[k] = values[k];
            }
          });
          let params = { ...head, diagramCombinationDetails: items, diagramCombinationQueries: querys };
          console.log('组合报表配置保存请求参数', params);
          if (isUpdate.value) {
            await defHttp.put({ url: '/api-online/diagram/diagramCombination/edit', params });
          } else {
            await defHttp.post({ url: '/api-online/diagram/diagramCombination/add', params });
          }
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      function setGroupTypeOptions(data) {
        if (data.dataSource) {
          let options = [];
          data.dataSource.forEach((item) => {
            let list = options.filter((it) => it.value == item.groupTxt);
            if (list.length <= 0) {
              options.push({
                value: item.groupTxt,
                label: item.groupTxt,
              });
            }
          });
          groupTypeOptions.value = options;
        }
      }

      function handleGroup() {
        openModal(true, {
          record: { id: '' },
          isUpdate: false,
          showFooter: true,
        });
      }

      function handleGroupSuccess(data) {
        if (data.isUpdate) {
          for (let i = 0; i < groupTypeOptions.value.length; i++) {
            if (groupTypeOptions.value[i].value == data.oldValue) {
              groupTypeOptions.value[i] = {
                value: data.newValue,
                label: data.newValue,
              };
              break;
            }
          }
        } else {
          let list = groupTypeOptions.value.filter((item) => item.value == data.newValue);
          if (list && list.length <= 0) {
            groupTypeOptions.value.unshift({
              value: data.newValue,
              label: data.newValue,
            });
          }
        }
      }

      function groupStyleChange(props) {
        props.triggerChange(props);
        // 组合展示风格变化 分组对应的组合展示风格跟着变动
        let rowIndex = props.rowIndex;
        let dataSource = onlGraphreportItemTable.dataSource.map((item) => item);
        let groupTxt = dataSource[rowIndex]['groupTxt'];
        dataSource.forEach((element) => {
          if (element.groupTxt === groupTxt) {
            element['groupStyle'] = props.value;
          }
        });
        onlGraphreportItemTable.dataSource = dataSource;
      }

      function combinationChange(props) {
        props.triggerChange(props);
        // 分组变化，分组对应的组合展示风格跟着变动
        let rowIndex = props.rowIndex;
        let dataSource = onlGraphreportItemTable.dataSource.map((item) => item);
        dataSource[rowIndex]['groupTxt'] = props.value;
        dataSource.forEach(function (element, i) {
          if (i !== rowIndex && element.groupTxt === props.value) {
            dataSource[rowIndex]['groupStyle'] = element.groupStyle;
            //onlGraphreportItemTable.dataSource[rowIndex]['groupTxt'] = element.groupTxt;
          }
        });
        onlGraphreportItemTable.dataSource = dataSource;
      }

      function combinationAddItem() {
        openModal(true, {
          isUpdate: false,
        });
      }

      function combinationEditItem(value) {
        openModal(true, {
          record: { name: value },
          isUpdate: true,
        });
      }

      return {
        formRef,
        activeKey,
        title,
        refKeys,
        confirmLoading,
        onlGraphreportItem,
        onlGraphreportQuery,
        onlGraphreportItemTable,
        onlGraphreportQueryTable,
        registerModal,
        registerForm,
        handleChangeTabs,
        handleSubmit,
        tableRefs,
        groupTypeOptions,
        groupStyleOptions,
        combinationAddItem,
        combinationChange,
        combinationEditItem,
        handleGroupSuccess,
        registerGroupModal,
        handleGroup,
        groupStyleChange,
      };
    },
  });
</script>
<style scoped></style>
